package com.rykj.widget;

import android.content.Context;
import android.os.CountDownTimer;
import android.util.AttributeSet;

import com.rykj.R;

import java.lang.ref.WeakReference;

import androidx.appcompat.widget.AppCompatButton;


/**
 * @author Daniel
 */
public class ValidCodeButton extends AppCompatButton {
    private ValidCodeCountDownTimer timer;


    public ValidCodeButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        timer = new ValidCodeCountDownTimer(this, 60000, 1000);
        init();
    }


    public void init() {
        setText("获取验证码");
        timer.cancel();
        setClickable(true);
        setSelected(false);
    }

    public void stop() {
        timer.cancel();
//        timer.onFinish();
        setText("获取验证码");
//        setClickable(true);
//        setSelected(false);
    }

    public void start() {
        timer.start();
    }

    /* 定义一个倒计时的内部类 */
    private static class ValidCodeCountDownTimer extends CountDownTimer {

        WeakReference<ValidCodeButton> mReference;

        public ValidCodeCountDownTimer(ValidCodeButton validCodeButton,
                long millisInFuture,
                long countDownInterval) {
            super(millisInFuture, countDownInterval);
            mReference = new WeakReference<ValidCodeButton>(validCodeButton);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if (mReference.get() != null) {
                mReference.get().setText(mReference.get().getContext()
                        .getString(R.string.btn_get_code_again,
                                "(" + millisUntilFinished / 1000 + ")"));
                mReference.get().setClickable(false);
            }
        }

        @Override
        public void onFinish() {
            if (mReference.get() != null) {
                mReference.get().setText(mReference.get().getContext()
                        .getString(R.string.btn_get_code_again, ""));
                mReference.get().setClickable(true);
                mReference.get().setSelected(false);
            }
        }
    }
}
